package com.black.quick.controller;

import com.black.quick.domain.QuickUser;
import com.black.quick.redis.RedisService;
import com.black.quick.service.GoodsService;
import com.black.quick.service.QuickUserService;
import com.black.quick.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author shy_black
 * @date 2019/7/25 15:05
 * @Description:
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    QuickUserService userService;

    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    /**
     * QPS == 122.8/sec
     *
     * @param model
     * @param user
     * @return
     */
    @RequestMapping(value="/to_list")
    public String list(Model model,QuickUser user) {
        model.addAttribute("user", user);
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        return "goods_list";
    }

    @RequestMapping("/to_detail/{goodsId}")
    public String detail(Model model, QuickUser user,
                         @PathVariable("goodsId") long goodsId) {
        model.addAttribute("user", user);
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods", goods);

        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int quickStatus = 0;
        int remainSeconds = 0;
        if (now < startAt) {//秒杀未开始
            quickStatus = 0;
            remainSeconds = (int) ((startAt - now) / 1000);
        } else if (now > endAt) {//秒杀已结束
            quickStatus = 2;
            remainSeconds = -1;
        } else {//进行中
            quickStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("quickStatus", quickStatus);
        model.addAttribute("remainSeconds", remainSeconds);
        return "goods_detail";
    }
}